package com.guigu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.mapper.StockMapper;
import com.guigu.pojo.Stock;
import com.guigu.service.StockService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
public class StockServiceImpl extends ServiceImpl<StockMapper, Stock> implements StockService {

    private static final Logger logger = LoggerFactory.getLogger(StockServiceImpl.class);

    @Override
    public Map<String, Object> getStockList(String name, String type, Integer page, Integer size) {
        QueryWrapper<Stock> wrapper = new QueryWrapper<>();
        if (name != null && !name.isEmpty()) {
            wrapper.like("stock_name", name);
        }
        if (type != null && !type.isEmpty()) {
            wrapper.like("product_type_list", type);
        }
        Page<Stock> stockPage = new Page<>(page, size);
        try {
            IPage<Stock> pageResult = baseMapper.selectPage(stockPage, wrapper);
            Map<String, Object> result = new HashMap<>();
            result.put("records", pageResult.getRecords());
            result.put("total", pageResult.getTotal());
            return result;
        } catch (Exception e) {
            logger.error("获取仓库列表失败", e);
            throw new RuntimeException("获取仓库列表失败");
        }
    }

    @Override
    @Transactional
    public boolean updateStock(Stock stock) {
        try {
            return this.updateById(stock);
        } catch (Exception e) {
            logger.error("更新仓库信息失败", e);
            throw new RuntimeException("更新仓库信息失败");
        }
    }
}